!function (e, $, mui) {
    "use strict";
	var config = {
	};
	
	// 定义页面
	var p = function(config) {
		var t = this;
		t.config = config;
		t.userInfo = null;
		t.params = {
			JobCode: null
		};
		t.page = {
			isRepeatCheck: false	// 是否是复盘页面
		};
		t.element = {
			JobCode: $('.JobCode'),
			listContainer: $('#list-container .list'),
			scanStart: $('#scan-start'),
			popupDetail: $('.popup-detail'),
			checkRepeat: $('#check-repeat'),
			dataUpload: $('#data-upload'),
			barcodeInput: $('#barcode-input'),
			barcodeAccept: $('#barcode-accept'),
			commit: $('#commit')
		};
		t.storage = {
			rfid: {},
			list: []
		};
		// 初始化
//		t.init();
	};
	
	var pt = p.prototype;
	
	pt.isRepeatCheck = function() {
		return this.page.isRepeatCheck;
	}
	
	// 页面初始化
	pt.init = function () {
		var t = this;
		t.userInit();
		// 页面加载
		t.pageLoad();
		// 列表加载
		t.listInit();
		// 事件监听
		t.listen();
	};
	
	// 事件初始化
	pt.listen = function() {
		var t = this;
		
		// 定义设备扫描返回处理
		window.readResult = function (result){
			if(result != '') {
				result = eval(result);
				// 存储返回值
				result.forEach(function (item) {
					t.storage.rfid[item] = item;
				});
				
				// 重构列表
				t.listBuild();
				
				// 检查未盘点数据
				var data = t.storage.list;
				
				var unCheck = 0;
				if(!isEmpty(data)) {
					for(var i = 0; i < data.length; i++) {
						if(data[i].state == '未盘点') {
							unCheck++;
						}
					}
				}
				
				if(unCheck == 0 && t.scanStart) {
					// 盘点完成
					mui.toast('扫描完成!');
					t.scanToggle();
				}
			}
		}
		
		// 开始/关闭扫描
		t.element.scanStart.on('tap', function () {
			t.scanToggle();
		});
		
		// 明细选择
		t.element.listContainer.on('tap', 'li', function () {
			$(this).siblings().removeClass('active').end().addClass('active');
		});
		
		// 查看明细
		t.element.popupDetail.on('tap', function () {
			var rowObj = t.element.listContainer.children('.active');
			if(rowObj.length == 0) {
				mui.toast('请选择查看的条目');
				return;
			}
			
			var data =rowObj.data();
			console.log('JOBCODE: '+ t.params.JobCode);
			console.log('DATA:'+JSON.stringify(data));
			
			pageChange({
				pageUrl: "detail.html",
				createNew: true,
				postData: data,
				aniShow: "fade-in"
			});
		});
		
		// 人工复盘
		t.element.checkRepeat.on('tap', function () {
			t.checkPageSwitch();
		});
		
		// 监听按键
		t.element.barcodeInput.on('keyup', function () {
			t.storage.activeRFID = $(this).val();
//			mui.toast(t.storage.activeRFID);
			
			// 滚动到顶部
			$('html, body').scrollTop(0);
			// 重构
			t.listBuild();
		});
		
		// 复盘确认
		t.element.barcodeAccept.on('tap', function () {
			var barcode = t.element.barcodeInput.val().trim();
			t.storage.rfid[barcode] = barcode;	// 存储
			t.storage.activeRFID = '';
			// 重构
			t.listBuild();
			t.element.barcodeInput.val('').focus();
		});
		
		// 盘点上传
		t.element.dataUpload.on('tap', function () {
			var rfid = t.storage.rfid;
			var list = t.storage.list;
		
			var jsonData = {
				"op": "Phone_SetStore_PanDian_ShangChuan",
				"JobCode": t.params.JobCode,
				"Main": []
			};
			
			// 检查需要上传的数据
			var uploadRFIDList = {};
			list.forEach(function (item) {
				if(item.state == '已扫描') {
					jsonData.Main.push({
						RFID: item.RFID
					});
					uploadRFIDList[item.RFID] = item.RFID;
				}
			});
			
			if(jsonData.Main.length == 0) {
				mui.toast('无可上传数据');
				return;
			}
			
			var opts = {
				url: "",
				addressUrl: "testline",
				requestType: "POST",
				pastDate: jsonData
			};
			
			plus.nativeUI.showWaiting();
			mui.toast('数据开始上传');
			crossDomainAjax(opts, function(data) {
				mui.toast('数据上传成功');
				plus.nativeUI.closeWaiting();
				console.log('Return:' + data);
				// 修改状态
				list.forEach(function (item, index) {
					if(uploadRFIDList[item.RFID]) {
						list[index].state = '已盘点';
					}
				});
				t.storage.list = list;
				
				t.listBuild();
				
				mui.toast("上传成功");
			}, function(s) {
				
			});
		});
		
		// 盘点完成
		t.element.commit.on('tap', function () {
			var jsonData = {
				"op": "Phone_SetStore_PanDian_Finish",
				"JobCode": t.params.JobCode,
				"Pid": userInfo.Pid
			}
		
			var opts = {
				url: "",
				addressUrl: "testline",
				requestType: "POST",
				pastDate: jsonData
			};
		
			console.log(JSON.stringify(opts));
			
			plus.nativeUI.showWaiting();
			crossDomainAjax(opts, function(data) {
				console.log(JSON.stringify(data));
				plus.nativeUI.closeWaiting();
				
				mui.toast('盘点完成');
				setTimeout(function () {
					// 刷新上一页
					plus.webview.currentWebview().opener().evalJS('PanDianMain();');
					// 关闭当前页
					closeCurrentWindow();
				}, 200);
		
			}, function(s) {
				
			});
		});
	};
	
	// 切换扫描启动关闭
	pt.scanToggle = function () {
		var t = this;
		var start = t.element.scanStart.data('start');
		t.scanStart = start = !start;
		t.element.scanStart.data('start', start);
		if(start) {
			mui.toast('开始扫描！');
			t.element.scanStart.text('停止扫描').addClass('active');
		} else {
			mui.toast('停止扫描！');
			t.element.scanStart.text('开始扫描').removeClass('active');
			var arr = [];
			for(var key in t.storage.rfid) {
				arr.push(key);
			}
		}
		plus.scanRFID(start);
	}
	
	// 盘点页面切换
	pt.checkPageSwitch = function () {
		var t = this;
		
		t.page.isRepeatCheck = !t.page.isRepeatCheck;	// 复盘页面
		$('.bottom-nav').toggle();
		t.element.commit.toggle();
		$('.mui-title').toggle();
		
		t.storage.activeRFID = ''; // 初始化
		
		if(t.isRepeatCheck()) {
			// 初始化输入框
			t.element.listContainer.addClass('repeat-check-container');
			t.element.barcodeInput.val('').focus();
		} else {
			t.element.listContainer.removeClass('repeat-check-container');
		}
	}
	
	pt.pageLoad = function () {
		var t = this;
		t.element.JobCode.text(t.params.JobCode);
	}
	
	// 列表初始化
	pt.listInit = function() {
		var t = this;
		t.element.listContainer.html('');
		t.page = {
			page: 0,
			perpage: 5,
			more: true
		};
		
		// 列表加载
		t.listLoad();
	};
	
	// 列表加载
	pt.listLoad = function() {
		var t = this;
		
		var jsonData = {
			"op": "Phone_GetStore_PanDian_Sub",
			"JobCode": t.params.JobCode
		}
	
		var opts = {
			url: "",
			addressUrl: "testline",
			requestType: "POST",
			pastDate: jsonData
		};
	
		console.log(JSON.stringify(opts));
		
		plus.nativeUI.showWaiting();
		crossDomainAjax(opts, function(data) {
			console.log(JSON.stringify(data));
			plus.nativeUI.closeWaiting();
			t.storage.list = data;
			t.listBuild();
			
			if (isEmpty(data)) {
				mui.toast("暂无数据");
			}
			
			mui('#list-container').pullRefresh().endPulldown();
	
		}, function(s) {
			
		});
		
		
	};
	
	// 列表初始化
	pt.listBuild = function () {
		var t = this;
		var data = t.storage.list;
		var rfid = t.storage.rfid;
		
		// 初始化
		t.element.listContainer.html('');
		if(!isEmpty(data)) {
			for(var i = 0; i < data.length; i++) {
				if(data[i].state == '未盘点' && rfid[data[i].RFID]) {
					data[i].state = '已扫描';
					var rowClass = 'item-checked';
				} else if(data[i].state == '未盘点') {
					var rowClass = 'item-unchecked';
				} else {
					var rowClass = 'item-checked';
				}
					
				if(data[i].state == '已扫描') {
					var stateText = '<span class="text-blue">已扫描</span>';
				} else if(data[i].state == '已完成' || data[i].state == '已盘点') {
					var stateText = '<span class="text-gray">'+data[i].state+'</span>';
				} else {
					var stateText = data[i].state;
				}
				
				if(t.storage.activeRFID) {
					data[i].RFIDText = (data[i].RFID+'').replace(t.storage.activeRFID, '<span class="text-blue">'+t.storage.activeRFID+'</span>');
					var top = true;
				} else {
					data[i].RFIDText = data[i].RFID;
					var top = false;
				}
				
				t.storage.list = data;
				
				var html = '<li class="'+rowClass+'" data-jobcode="'+t.params.JobCode+'" data-rfid="'+data[i].RFID+'">';
				html += '<span>RFID：</span><em>'+data[i].RFIDText+'</em><br />';
				html += '<span>货位：</span><em>'+data[i].HuoWei+'</em><br />';
				html += '<span>状态：</span><em>'+stateText+'</em><br />';
				html += '</li>';
				if(top || (t.storage.activeRFID && data[i].state =='未盘点')) {
					t.element.listContainer.prepend(html);
				} else {
					t.element.listContainer.append(html);
				}
			}
		}
	};
	
	// 用户信息初始化
	pt.userInit = function() {
		var t = this;
	};
	
	e.page = new p(config);
	mui.init({
		pullRefresh: {
			container: '#list-container',
			down: {
				style: 'circle',
				callback: function () {
					e.page.listInit();
				}	// 下拉刷新
			}
		}
	});

	mui.plusReady(function () {
		e.page.params.JobCode = getQueryString("itemId");
		e.page.init();
		mui.init({
			beforeback: function () {
				if(e.page.isRepeatCheck()) {
					e.page.checkPageSwitch();
					return false;
				}
			}
		});
	});
		

}(window, $, mui);